<template>
  <content-l-r title="角色">
    <div slot="body-left" class="bread bread-left">
      <el-row>
        <el-input
          placeholder="回车查询角色"
          clearable
          prefix-icon="el-icon-search"
          @keyup.enter.native="queryRoles($event)"
          v-model="queryParams.name">
        </el-input>
        <!--@blur="queryRoles($event)"-->
      </el-row>
      <el-row>
        <el-table v-loading="queryParamsLoading"
                  :data="table.rows"
                  style="width: 100%"
                  @row-click="handleRowClick"
                  :highlight-current-row="true"
        >
          <el-table-column
            prop="name"
            label="角色列表"
            align="left">
            <template slot-scope="scope">
              <div class="row-role-name">
                <i :class="scope.row.icon=='el-icon-circle-plus-outline'?'row-blue '+scope.row.icon:scope.row.icon">
                  {{scope.row.name}}</i>
              </div>
              <div style="float: right" v-show="scope.row.icon!='el-icon-circle-plus-outline'">
                <a class="mimi-icon" @click.stop="handleRoleEdit(scope.row.id,scope.row)" title="编辑">
                  <i class="el-icon-edit"></i>
                </a>&nbsp;
                <a class="mimi-icon" @click.stop="handleRoleDelete(scope.row.id,scope.row)" title="删除">
                  <i class="el-icon-delete"></i>
                </a>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="bottom-area"></div>
      </el-row>
      </el-col>
    </div>
    <div slot="body-right" class="bread bread-right">
      <el-row>
        <el-col :span="12">
          <template>
            <p style="color: #909399" v-if="currentRole.name!=undefined">{{currentRole.name}}<span
              style="color: #99a9bf; font-size: 13px"> {{currentRole.description}}</span></p>
            <p style="color: #909399" v-else>没有角色被选中</p>
          </template>
          </p>
        </el-col>

        <el-col :span="12">
          <div style="margin-top: 13px">
            <div style="float: right;">
              <el-button type="primary" plain size="mini" @click="handelPermissionChange" icon="el-icon-upload2"
                         style="width: 100%">保存修改
              </el-button>
            </div>
            <div style="float: right;margin-right: 10px">
              <el-switch
                v-model="collapseFlag"
                active-color="#67C23A"
                inactive-color="#F56C6C"
                @change="handleTreeToggle">
              </el-switch>
              <span style="color: #606266;font-size: 14px;">{{collapseFlag?'已展开':'已收起'}}</span>
            </div>
          </div>
        </el-col>
      </el-row>
      <div style="height: 10px; border-bottom: 1px  solid #DCDFE6"></div>
      <el-row style="padding: 15px" v-loading="loading">
        <el-tree
          :data="rolePermissionData"
          show-checkbox
          highlight-current
          node-key="id"
          ref="tree"
          :props="defaultProps">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span> <i class="el-icon-edit"></i> {{ data.name }}</span>
          </span>
          </span>
        </el-tree>
      </el-row>
      <el-dialog
        title="角色详情"
        :visible.sync="dialogVisible"
        width="30%">
        <el-form :model="editRole" label-position="left" :rules="rules" ref="editRole">
          <el-form-item label="" prop="name">
            <el-input v-model="editRole.name" placeholder="角色名称"></el-input>
          </el-form-item>
          <el-form-item label="" prop="description">
            <el-input v-model="editRole.description" placeholder="角色描述"></el-input>
          </el-form-item>
          <p style="color: #909399">角色名称全局不能重复</p>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handelEditRoleDialogConfirm('editRole')" style="width: 100%">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </content-l-r>
</template>

<script>
  import util from '../../utils/util'
  import ContentLR from '../../components/ContentLR.vue'
  import {mapState, mapActions} from 'vuex'
  import {Role, Permission} from '../../utils/resource'
  import {deleteConfirm, showSaveResponse, validFieldExists, validateForm} from '../../utils/element-helper'


  export default {
    name: 'role',
    components: {
      ContentLR: ContentLR
    },
    data() {
      return {
        queryParams: {
          name: null,
          sc: "name asc",
        },
        table: {
          rows: [],
          pageNumber: 1,
          pageSize: 1000,
        },
        queryParamsLoading: false,
        loading: false,
        dialogVisible: false,
        currentRole: {
          status: 1
        },
        editRole: {},
        collapseFlag: false,
        roleData: [],
        rules: {
          name: [
            {required: true, message: '角色名称不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
        },
        rolePermissionData: [],
        checkedRolePermissionData: [1],
        defaultProps: {
          children: 'children',
          label: 'name',

        }
      }
    },
    created() {
      this.queryRoles()
      this.loadPermissions()
    },
    computed: {},
    methods: {
      async queryRoles() {
        if (this.queryParams.name === "" || this.queryParams.name == null) {
          delete  this.queryParams["name"]
        }
        this.queryParamsLoading = true
        await Role.paging(this)
        this.table.rows.push({
          id: undefined,
          name: '新增角色',
          description: "",
          icon: "el-icon-circle-plus-outline",
        })
        this.currentRole = {}
        this.$nextTick(() => {
          this.queryParamsLoading = false
        })
      },
      handleRoleEdit(id, row) {
        this.dialogVisible = true
        this.currentRole = Object.assign({}, row)
        this.editRole = Object.assign({}, row)
        this.clearRoleForm()
        this.isNew = false
      },
      handleRowClick(row, event, column) {
        //选中角色行
        if (row.id != undefined && row.name != '新增角色') {
          this.currentRole = Object.assign({}, row)
          this.loadRolePermissions()
        } else {
          this.handleAddRole()
        }
      },
      handleAddRole() {
        //新增角色
        this.dialogVisible = true
        this.currentRole = {}
        this.editRole = {}
        this.clearRoleForm()
        this.isNew = true
      },
      clearRoleForm() {
        //数据绑定完毕后再重置表单，否则form组件还未生成
        this.$nextTick(() => {
          this.$refs['editRole'].clearValidate()
        })
      },
      validateExists(rule, value, callback) {
        validFieldExists(rule, value, callback, this.currentRole[rule.field] != value || this.isNew, (rule, value) => Role.exists(rule, value))
      },
      async loadPermissions() {
        this.loading = true
        let res = await Permission.tree()
        this.rolePermissionData = res.data
        this.$nextTick(() => {
          this.loading = false
        })
      },
      async loadRolePermissions() {
        this.loading = true
        let res = await Role.rolePermission(this.currentRole.name)
        let checkedAr = []
        for (let i = 0; i < res.data.length; i++) {
          let obj = res.data[i]
          checkedAr.push(obj.id)
        }
        this.checkedRolePermissionData = checkedAr
        this.$refs.tree.setCheckedKeys(checkedAr)
        this.$nextTick(() => {
          this.loading = false
        })
      },
      handelEditRoleDialogConfirm(formName) {
        return validateForm(this, formName, () => {
          showSaveResponse(this, () => Role.save(this.editRole, this.isNew ? 'post' : 'put'), (res) => {
            this.queryRoles()
            this.dialogVisible = false
          })
        })
      },
      handleRoleDelete(id, row) {
        deleteConfirm(this, {}, () => Role.del(row.id), (resp) => this.queryRoles())
      },
      async handelPermissionChange() {
        if (this.currentRole.id == undefined) {
          this.$message({
            type: 'error',
            message: '请在左侧列表选择角色!'
          })
          return
        }
        let tempFrom = {
          roleId: this.currentRole.id,
          permissionIds: this.$refs.tree.getCheckedKeys()
        }
        //添加父节点
        tempFrom.permissionIds = tempFrom.permissionIds.concat(this.$refs.tree.getHalfCheckedKeys())
        this.loading = true
        showSaveResponse(this, () => Role.updateRolePermissions(tempFrom), (res) => this.loading = false)
      },
      //展开收起所有树节点
      handleTreeToggle(data) {
        for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
          this.$refs.tree.store._getAllNodes()[i].expanded = data;
        }
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

  .bread {
    background-color: white;
    border-radius: 2px;
    padding: 15px;
    -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, .2);
    box-shadow: 0 0 3px rgba(0, 0, 0, .2);
    height: 100%;
  }

  .bread-left {
    margin-right: 5px;
  }

  .bread-right {
    margin-left: 5px;
  }

  .row-role-name {
    font-size: 16px;
    cursor: pointer;
    float: left;
  }

  .row-blue {
    color: #42A1FF;
  }

  .bottom-area {
    height: 25px;
  }

  .mimi-icon {
    cursor: pointer;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
